﻿using System;
using System.Diagnostics;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using YJKCodeBase.WinForm;

namespace YJKFamilyLibManager.ForProject
{
	[Regeneration(RegenerationOption.Manual)]
	[Transaction(TransactionMode.Manual)]
	public class CmdFamilyManagerForPro : YJKCommandManual
	{
		protected override Result YJKExcute(ExternalCommandData cmdData, ref string message, ElementSet elements)
		{
			try
			{
				Process currentProcess = Process.GetCurrentProcess();
				if (currentProcess != null)
				{
					IntPtr mainWindowHandle = currentProcess.MainWindowHandle;
					WindowHandle owner = new WindowHandle(mainWindowHandle);
					try
					{
						for (;;)
						{
							DlgFamilyManagerForPro dlgFamilyManagerForPro = new DlgFamilyManagerForPro(cmdData);
							if (dlgFamilyManagerForPro.ShowDialog(owner) == DialogResult.OK)
							{
								try
								{
									FamilySymbol familySymbol = dlgFamilyManagerForPro.DbFamilySymbo.Create(cmdData.Application.ActiveUIDocument.Document);
									this.m_uiApp.ActiveUIDocument.PromptForFamilyInstancePlacement(familySymbol);
									continue;
								}
								catch (Autodesk.Revit.Exceptions.OperationCanceledException)
								{
									continue;
								}
								catch (Exception)
								{
									MessageBox.Show("布置失败。可能原因：1、当前视图下不能创建族实例；2、\r\n该族的规格(类型)没有\"创建实例\"命令。", "族库管理");
									continue;
								}
								break;
							}
							break;
						}
						goto IL_8D;
					}
					catch (Exception ex)
					{
						MessageBox.Show(ex.Message);
						goto IL_8D;
					}
				}
				MessageBox.Show("未能得到当前Revit进程！");
				IL_8D:;
			}
			catch (Exception ex2)
			{
				MessageBox.Show(ex2.Message);
			}
			return base.YJKExcute(cmdData, ref message, elements);
		}
	}
}
